using Aspose.Words.Lists;
using DotNetCore.CAP;
using NP.BPMReportPlatform.Common;
using NP.BPMReportPlatform.CourseTrain.Enums;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.EmailHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Business.Cadre;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.RecurringJobs;
using NP.BPMReportPlatform.RecurringJobs.Dto;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static NP.BPMReportPlatform.Cadre.Enum.CadreEnum;

namespace NP.BPMReportPlatform.CourseTrain
{
    /// <summary>
    /// 培训任务同步接口
    /// </summary>
    public class CourseTrainTaskSyncJob : BpmReportPlatformRecurringJob, ICourseTrainTaskSyncJob
    {
        private readonly SqlSugarClient _db, _dbPlatform;
        private readonly IEmailAPPService _emailAPPService;
        private ICapPublisher _capBus;
        private readonly ICommonService _commonService;
        private readonly ICourseTrainTaskService _courseTrainTaskService;

        public CourseTrainTaskSyncJob(ISqlSugarAppService sqlSugarAppService, IEmailAPPService emailAPPService, ICapPublisher capPublisher, ICommonService commonService, ICourseTrainTaskService courseTrainTaskService)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _emailAPPService = emailAPPService;
            _capBus = capPublisher;
            _commonService = commonService;
            _courseTrainTaskService = courseTrainTaskService;
        }

        /// <summary>
        /// 定时任务入口
        /// </summary>
        /// <returns></returns>
        public Task CourseTrainTaskJob()
        {
            var syncTaks = _db.Queryable<CourseSyncTaskEntity>().Where(t => t.Status == 1).ToList();
            string dateString = DateTime.Now.ToString("yyyy-MM-dd");
            DateTime date = DateTime.Today;

            foreach (var item in syncTaks)
            {
                // 判断今天是否是培训心得填写日期
                if (item.ExperienceDate == date)
                {
                    SendCourseEmail(CourseTrainEmailEnum.学习心得提醒邮件, item.CourseTrainId);
                    item.ExperienceDate = item.ExperienceDate?.AddMonths(1);
                    _db.Updateable(item).ExecuteCommandAsync();
                }

                if (dateString == item.SummarDate1)
                {
                    SendCourseEmail(CourseTrainEmailEnum.培训总结提醒邮件, item.CourseTrainId);
                }
                else if (dateString == item.SummarDate2)
                {
                    SendCourseEmail(CourseTrainEmailEnum.培训总结提醒邮件, item.CourseTrainId);
                }

            }

            _courseTrainTaskService.SyncInstractor();
            _courseTrainTaskService.SyncTrainCourses();

            return Task.CompletedTask;
        }

        /// <summary>
        /// 推送邮件
        /// </summary>
        public async Task SendCourseEmail(CourseTrainEmailEnum type, string id)
        {
            string topic = string.Empty;
            string templateName = string.Empty;
            string to = string.Empty;
            string cc = string.Empty;
            string url = ConfigManager.HRBPMReportUrl + "/report/course-train-oversea/course-oversea-list";
            switch (type)
            {
                case CourseTrainEmailEnum.学习心得提醒邮件:
                    var courseOverSea = await _db.Queryable<CourseOverSeaTrainEntity>().Where(t => t.CourseTrainId == id).FirstAsync();
                    var summarys = await _db.Queryable<CourseSummaryEntity>().Where(t => t.CourseTrainId == id).ToListAsync();
                    var experience = summarys.FirstOrDefault(t => t.SummaryType == 1 && t.CreateTime?.ToString("yyyy-MM") == DateTime.Today.ToString("yyyy-MM"));
                    var tousers = new List<Users>();
                    object oa;
                    if (experience == null)
                    {
                        topic = $"学习心得提醒邮件";
                        templateName = "LearningExperience.cshtml";
                        tousers = await _dbPlatform.Queryable<Users>().Where(t => courseOverSea.WorkNumber == t.WorkNumber).ToListAsync();
                        to = tousers?.FirstOrDefault()?.Email;
                        oa = new { CourseUser = courseOverSea.DispatchUserName, CourseTitle = courseOverSea.CourseTrainCode, Url = url };
                        SendEmail(templateName, topic, to, cc, oa);
                    }
                    break;
                case CourseTrainEmailEnum.培训总结提醒邮件:
                    courseOverSea = await _db.Queryable<CourseOverSeaTrainEntity>().Where(t => t.CourseTrainId == id).FirstAsync();
                    var endDate = _db.Queryable<CourseOverSeaTrainDetailEntity>().Where(t => t.InstanceNumber == courseOverSea.InstanceNumber).Max(t => t.EndTime);
                    summarys = await _db.Queryable<CourseSummaryEntity>().Where(t => t.CourseTrainId == id).ToListAsync();
                    var summary = summarys.FirstOrDefault(t => t.SummaryType == 1 && t.CreateTime?.ToString("yyyy-MM") == DateTime.Today.ToString("yyyy-MM"));
                    if (summary == null)
                    {
                        topic = $"培训总结提醒邮件";
                        templateName = "LearningSummary.cshtml";
                        tousers = await _dbPlatform.Queryable<Users>().Where(t => courseOverSea.WorkNumber == t.WorkNumber).ToListAsync();
                        to = tousers?.FirstOrDefault()?.Email;
                        oa = new { CourseUser = courseOverSea.DispatchUserName, CourseTitle = courseOverSea.CourseTrainCode, Url = url, EndDate = endDate?.AddMonths(1).ToString("yyyy年MM月dd日") };
                        SendEmail(templateName, topic, to, cc, oa);
                    }
                    break;
                case CourseTrainEmailEnum.海外培训审批通过提醒签协议:
                    courseOverSea = await _db.Queryable<CourseOverSeaTrainEntity>().Where(t => t.CourseTrainId == id).FirstAsync();
                    topic = $"海外培训审批通过提醒提醒邮件";
                    templateName = "CourseOverSeaTrainNotic.cshtml";
                    tousers = await _dbPlatform.Queryable<Users>().Where(t => courseOverSea.WorkNumber == t.WorkNumber).ToListAsync();
                    to = tousers?.FirstOrDefault()?.Email;
                    oa = new { CourseUser = courseOverSea.CreateUserName, CourseTitle = courseOverSea.CourseTrainCode, Url = url };

                    SendEmail(templateName, topic, to, string.Empty, oa);
                    break;
                case CourseTrainEmailEnum.培训考证附件上传前:
                    var courseTrain = await _db.Queryable<CourseTrainTaskEntity>().Where(t => t.CourseTrainTaskId == id).FirstAsync();
                    if (courseTrain.IsObtainCert == true)
                    {
                        topic = $"培训考证附件待上传提醒邮件";
                        templateName = "CertUpdateBeforeNotice.cshtml";
                        var courseTrainUserDetails = await _db.Queryable<CourseTrainUserDetailEntity>().Where(t => t.CourseTrainTaskId == id).ToListAsync();
                        var courseTrainUsers = courseTrainUserDetails.Select(t => t.TrainUserWorknumber).ToList();
                        tousers = await _dbPlatform.Queryable<Users>().Where(t => courseTrainUsers.Contains(t.WorkNumber)).ToListAsync();

                        foreach (var user in tousers)
                        {
                            oa = new { TrainUser = user.UserName, CourseTitle = courseTrain.CourseTrainCode, Url = ConfigManager.HRBPMReportUrl + "/report/course-train/course-cert-list" };
                            to = user.Email;
                            SendEmail(templateName, topic, to, string.Empty, oa);
                        }
                    }
                    break;
                case CourseTrainEmailEnum.培训考证附件上传后:
                    var courseTrainUserDetail = await _db.Queryable<CourseTrainUserDetailEntity>().Where(t => t.CourseTrainUserDetailId == id).FirstAsync();
                    topic = $"培训考证附件已上传提醒邮件";
                    templateName = "CertNotice.cshtml";
                    var CourseTrainTask = await _db.Queryable<CourseTrainTaskEntity>().Where(t => t.CourseTrainTaskId == courseTrainUserDetail.CourseTrainTaskId).FirstAsync();
                    var worknumbers = _commonService.GetUserHRBPFilter(CourseTrainTask.WorkNumber, Contract.Dtos.RelationshipTypeEnum.培训专员);
                    tousers = await _dbPlatform.Queryable<Users>().Where(t => worknumbers.Contains(t.WorkNumber)).ToListAsync();
                    to = tousers?.FirstOrDefault()?.Email;
                    oa = new { TrainUser = courseTrainUserDetail.TrainUser, CourseTitle = courseTrainUserDetail.CourseTrainCode, CertName = courseTrainUserDetail.CertName };
                    SendEmail(templateName, topic, to, cc, oa);
                    break;
                default: break;
            }
        }

        private void SendEmail(string templateName, string topic, string to, string cc, object o)
        {
            string content = string.Empty;
            if (!string.IsNullOrEmpty(templateName))
            {
                content = _emailAPPService.GenerateEmailTemplate(templateName, o);
            }

            // && ConfigManager.NeedSendEmail
            if (!string.IsNullOrEmpty(content) && !string.IsNullOrEmpty(to))
            {
                // TODO: 测试，只发给liya,上线前要去掉
                // topic = topic + ";" + to;
                // content += "cc" + cc;
                // content += "to" + to;
                // cc = "liya.li@movit-tech.com;ruby.yang@movit-tech.com;tiger.zhou@movit-tech.com";
                // to = "limn.qin@movit-tech.com";
                var email = new SendEmailSimpleDto()
                {
                    To = to,
                    Subject = topic,
                    Body = content,
                    CC = cc,
                };

                _capBus.PublishAsync("bpmnew.EmailAppService.SendEmailAsync", email);

            }
        }
    }
}
